﻿using System;
using System.Collections.Generic;
//using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Timers;
using System.Threading;
using System.Windows.Automation;
using System.IO;
using System.DirectoryServices.AccountManagement;
using System.Collections.ObjectModel;
using System.Collections;
using System.Reflection;

namespace RejectRDP
{
    class RDP
    {

        // http://msdn.microsoft.com/en-us/library/ms171548.aspx
        // http://bytes.com/topic/c-sharp/answers/631421-set-focus-program-win32
        // http://pinvoke.net/default.aspx/user32/FindWindowEx.html
        // http://pinvoke.net/default.aspx/user32/FindWindow.html
        // http://www.prodigyproductionsllc.com/articles/automation/windows-automation-with-c/
        // http://msdn.microsoft.com/en-us/magazine/cc163288.aspx

        /*
            OLO\YZA0541t wants to connect to this machine.
            Click OK to disconnect your session immediately or click cancel to stay connected.
            Otherwise, you will be disconnected in 30 seconds. 
        */

        // Variables        
        string strMessage;
        string[] arrUserDetails;
        DisplayMessage dpmMessage;

        // Property's
        public string _strMessage
        {
            set { this.strMessage = value; }
            get { return this.strMessage; }
        }

        private string[] _arrUserDetails
        {
            set { this.arrUserDetails = value; }
            get { return this.arrUserDetails; }
        }


        /// <summary>
        /// Main method
        /// </summary>
        public void Init()
        {
            // Start all actions from here
            checkForRDPdialog();
            //writeLogFile(_strMessage);

        }

        /// <summary>
        /// Check for active incoming rdp window and take action if so
        /// </summary>
        private void checkForRDPdialog()
        {
            try
            {
                // Get root element "desktop"
                AutomationElement aeDesktop = AutomationElement.RootElement;

                // Get the RDP window
                AutomationElement aeRDP = aeDesktop.FindFirst(TreeScope.Children, new PropertyCondition(AutomationElement.NameProperty, "Remote Desktop Connection"));
                Thread.Sleep(100);

                // If the window exists continue
                if (aeRDP != null)
                {
                    // Get all text controls. This one will contain the message displayed to the user
                    AutomationElementCollection aeAllTextControls = aeRDP.FindAll(TreeScope.Children, new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Text));
                    if (aeAllTextControls != null)
                    {
                        foreach (AutomationElement aeElement in aeAllTextControls)
                        {
                            if (aeElement.Current.Name.ToLower().Contains("wants to connect to this machine"))
                            {
                                //MessageBox.Show("This is captured !!! proceed to kick! \r\n" + aeElement.Current.Name);
                                _strMessage = aeElement.Current.Name.ToLower().Trim();

                                // Find the "Cancel" button we need to kick the user. There are only two buttons defined in
                                // the dialog so we can use the findfirst method instead of the all.
                                AutomationElement aeCancelButton = aeRDP.FindFirst(TreeScope.Subtree, new PropertyCondition(AutomationElement.NameProperty, "Cancel"));
                                if (aeCancelButton != null)
                                {
                                    // Deny the logon
                                    InvokePattern ipClickCancel = (InvokePattern)aeCancelButton.GetCurrentPattern(InvokePattern.Pattern);
                                    ipClickCancel.Invoke();
                                    Thread.Sleep(1500);
                                    // Write logfile
                                    writeLogFile(_strMessage);
                                    return;
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Something went wrong\r\n" + ex.Message);
            }
        }

        /// <summary>
        /// Write intruder actions to log files.
        /// </summary>
        /// <param name="_strMessage"></param>
        public void writeLogFile(string __strMessage)
        {
            try
            {
                string strLogFileFolder = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + @"\Intruders";
                string strFileName = "Intruders.log";
                string strOutPutFile = strLogFileFolder + @"\" + strFileName;
                DateTime dt = DateTime.Now;
                string strDateAndTime = (String.Format("{0:G}", dt)).Replace(":", "_");


                if ((__strMessage.Length > 0) && (__strMessage != null))
                {
                    string strIntruderName = getUserNameFromDialogText(__strMessage);

                    if ((strIntruderName.Length > 0) && (strIntruderName != null))
                    {
                        if (!Directory.Exists(strLogFileFolder))
                        {
                            Directory.CreateDirectory(strLogFileFolder);
                        }

                        // Write the log file
                        string strLogFileLine = strDateAndTime + "\t" + "Intruder name: " + strIntruderName + "\r\n";
                        File.AppendAllText(strOutPutFile, strLogFileLine);

                        // Get some more info
                        Hashtable arlUserDetails = getUserInfoFromAD(strIntruderName);
                        if (arlUserDetails != null)
                        {
                            //_arrUserDetails = (string[])arlUserDetails.ToArray(typeof(string));

                            foreach (DictionaryEntry strTemp in arlUserDetails.Keys)
                            {
                                MessageBox.Show("Let's roll ");
                                string key = strTemp.Key.ToString().Trim();
                                string waarde= strTemp.Value.ToString().Trim();
                                MessageBox.Show("Key: " + key + " waarde: " + waarde);
                                if (waarde.Length > 0) {
                                    File.AppendAllText(strOutPutFile, key + @"\t" + waarde + "\r\n");
                                    MessageBox.Show("toegevoegd aan de textfile");
                                }

                            }

                            //End of section devider
                            File.AppendAllText(strOutPutFile, "\r\n\r\n");

                            //foreach (string strTemp in _arrUserDetails)
                            //{
                            //    File.AppendAllText(strOutPutFile, strTemp + "\r\n");
                            //}
                            //// End of section devider
                            //File.AppendAllText(strOutPutFile, "\r\n\r\n");
                        }

                        // Display message on screen
                        displayIntruder(_arrUserDetails);
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Something went wrong\r\n" + ex.StackTrace);
            }
        }


        /// <summary>
        /// Get the username from the dialogbox showed by RDP
        /// </summary>
        /// <param name="_strMessage"></param>
        /// <returns>string</returns>
        private string getUserNameFromDialogText(string __strMessage)
        {
            try
            {

                if (__strMessage.Length > 0)
                {
                    string[] tempAll = __strMessage.ToLower().Trim().Split();
                    var item = Array.Find(tempAll, s => s.Contains("dian"));
                    return item.ToString();
                }

                return null;
            }
            catch (Exception ex)
            {
                throw new Exception("Something went wrong\r\n" + ex.Message);
            }
        }

        /// <summary>
        /// Get the AD username of the intruder
        /// </summary>
        /// <param name="_strSAMACCOUNT"></param>
        /// <returns>string</returns>
        private Hashtable getUserInfoFromAD(string _strSAMACCOUNT)
        {

            ProcessStartInfo temp = new ProcessStartInfo();
            temp.Arguments = "Ik ben een held !!!";
            temp.Domain = "DianenmaN Domain";
            temp.FileName = "Dit is de filename property";

            PropertyInfo[] propertyInfos;
            propertyInfos = temp.GetType().GetProperties();

            //object objtemp;

            //MyNamespace.MyClass.SName = "Sheetal";
            //MyNamespace.MyClass myCls = new MyNamespace.MyClass();
            //PropertyInfo pi = myCls.GetType().GetProperty("SName");
            //string value = (string)(pi.GetValue(null, null));
            //Response.Write(value);

            foreach (PropertyInfo prop in propertyInfos)
            {

                string strValue = prop.GetValue(temp, null).ToString();
                    
                    //(string)(prop.GetValue(null,null));
                
                //prop.GetValue(null, null));
                //object objReturn = new object();
                //prop.GetValue(objtemp, null);
                Debug.WriteLine("Value prop: " + prop.Name.ToString() + " - " + strValue);

            }

            Hashtable hstUserItems = new Hashtable();

            return hstUserItems;


//            try
//            {
//                if ((_strSAMACCOUNT.Length > 0) && (_strSAMACCOUNT != null))
//                {
//                    Hashtable hstUserItems = new Hashtable();
//                    //PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
//                    PrincipalContext ctx = new PrincipalContext(ContextType.Machine);

//                    // Find intruder
//                    UserPrincipal user = UserPrincipal.FindByIdentity(ctx, _strSAMACCOUNT);

//                    if (user != null)
//                    {
//                        // Receive all properties
//                        PropertyInfo[] propertyInfos;
//                        propertyInfos = typeof(UserPrincipal).GetProperties();

//                        Debug.Flush();

//                        // Loop through each property
//                        foreach (PropertyInfo prop in propertyInfos)
//                        {
//                            if (prop.PropertyType == typeof(string))
//                            {
//                                //string strPropValue = (string)prop.GetValue(user, null);
//                                //strPropValue = strPropValue.Trim();
//                                //MessageBox.Show("Dit is de value: " + strPropValue);
//                                //if ((strPropValue.Length > 0) && (strPropValue != null) && (strPropValue != ""))
//                                //{

//                                object objReturn = new object();
//                                string strValue = Convert.ToString(prop.GetValue(objReturn, null));
//                                Debug.WriteLine("Value prop: " + prop.Name.ToString() + " = " + strValue );

//                                if ((strValue.Length > 0) && (strValue != null))
//                                {
//                                    hstUserItems.Add(prop.Name, strValue);
//                                }

////                                hstUserItems.Add(prop.Name, (string)prop.GetValue(prop.Name, null));

//                                    //MessageBox.Show(prop.Name + "waarde opvragen");
//                                    //object test = prop.GetValue(user, null);
//                                    //MessageBox.Show("Waarde is: " + test.ToString());
//                                    //arlUserDetails.Add(prop.Name + "\t" + prop.GetValue(user, null));
//                                    //MessageBox.Show("Toegevoegd aan array");
//                                //}
//                            }
//                        }


//                        return hstUserItems;
//                    }
//                }

//                return null;
//            }
//            catch (Exception ex)
//            {
//                throw new Exception (ex.StackTrace);
//            }
        }

        /// <summary>
        /// Display intruder message window
        /// </summary>
        /// <param name="_strMessage"></param>
        public void displayIntruder(string[] __strUserDetails)
        {
            if ((__strUserDetails.Length > 0) && (__strUserDetails != null))
            {
                dpmMessage = new DisplayMessage(__strUserDetails);
                dpmMessage.Show();
            }
        }
    }
}
